package com.aefottt.struggle_star.activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Build;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.transition.Explode;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.TimePicker;

import androidx.appcompat.widget.PopupMenu;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.aefottt.struggle_star.DataListenerManager;
import com.aefottt.struggle_star.R;
import com.aefottt.struggle_star.adapter.SubTaskRecyclerAdapter;
import com.aefottt.struggle_star.base.BaseActivity;
import com.aefottt.struggle_star.bean.DataBean;
import com.aefottt.struggle_star.bean.ListBean;
import com.aefottt.struggle_star.bean.SubTaskBean;
import com.aefottt.struggle_star.bean.TaskBean;
import com.aefottt.struggle_star.util.DateUtil;
import com.aefottt.struggle_star.util.DisplayUtil;
import com.aefottt.struggle_star.view.AchieveView;

import org.litepal.LitePal;

import java.util.Calendar;
import java.util.List;

public class DataActivity extends BaseActivity {
    private AchieveView achieveView;
    private Toolbar toolbar;
    private ImageView ivSend, ivDelete;
    private EditText etTitle;
    private TextView selectList, selectReminderTime;

    private RecyclerView rvSubTask;

    private PopupWindow popupImportant;
    private ImageView ivImpA, ivImpB, ivImpC, ivImpD;
    private TextView impA, impB, impC, impD;

    // 当前界面是否为新建界面
    private boolean isAddData;
    private TaskBean taskBean;
    private int listId; // 父类清单id

    private int year, month, day;

    public interface OnDataActivityListener{
        void onCreate(TaskBean taskBean);
        void onDelete(TaskBean taskBean);
    }

    @Override
    protected int getLayoutId() {
        getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
        Intent intent = getIntent();
        if (intent.getSerializableExtra("DataBean") == null){
            // 新建数据
            isAddData = true;
            getWindow().setEnterTransition(new Explode());
            getWindow().setExitTransition(new Explode());
            listId = intent.getIntExtra("listId", 0);
            if (intent.getBooleanExtra("isFirst", false)){
                taskBean = new TaskBean(listId, 1);
            }else if (listId != 0) {
                taskBean = new TaskBean(listId);
            }else {
                throw new IllegalArgumentException("未传入ListId");
            }
        }else {
            // 查看数据
            taskBean = (TaskBean) intent.getSerializableExtra("DataBean");
        }
        return R.layout.activity_data;
    }

    @Override
    protected void initListener(){
        achieveView.setOnAchievedViewListener(state -> {
            // 这里只有查看数据时才可点击，所以taskBean可保存
            if (state == AchieveView.ACHIEVED_STATE){
                taskBean.setIsAchieved(1);
            }else if (state == AchieveView.NOT_ACHIEVED_STATE){
                taskBean.setIsAchieved(0);
            }
            taskBean.save();
            DisplayUtil.changeEtContent(etTitle, taskBean.getDataTitle(),
                    taskBean.getIsAchieved());
        });
        // 设置点击事件
        toolbar.setNavigationOnClickListener(v -> openNotSaveDialog());
        if (Build.VERSION.SDK_INT >= 21) { // 5.0以上系统
            int[] attrs = {android.R.attr.selectableItemBackgroundBorderless};
            TypedArray typedArray = getTheme().obtainStyledAttributes(attrs);
            int resourceId = typedArray.getResourceId(0, 0);
            ivSend.setBackgroundResource(resourceId);
        }
        // 创建New Task
        ivSend.setOnClickListener(v -> {
            if (taskBean.getImportantLevel() == DataBean.IMPORTANT_LEVEL_NONE){
                // 设置默认重要性
                taskBean.setImportantLevel(DataBean.IMPORTANT_LEVEL_C);
            }
            taskBean.save();
            DataListenerManager.getInstance(this).onCreate(taskBean);
            finishAfterTransition();
        });
        // Delete Task
        ivDelete.setOnClickListener(v -> {
            // 删除该数据
            SpannableString exitStr = new SpannableString("删除");
            exitStr.setSpan(new ForegroundColorSpan(Color.RED), 0, 2, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            SpannableString cancelStr = new SpannableString("取消");
            cancelStr.setSpan(new ForegroundColorSpan(Color.GRAY), 0, 2, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("确定永久删除<"+taskBean.getDataTitle()+">吗？")
                    .setPositiveButton(exitStr, (dialog, which) -> {
                        DataListenerManager.getInstance(this).onDelete(taskBean);
                        finishAfterTransition();
                    })
                    .setNegativeButton(cancelStr, (dialog, which) -> dialog.dismiss())
                    .create().show();
        });
        // 显示选择Important的PopupWindow
        ivImpA.setOnClickListener(v -> popupImportant.showAsDropDown(ivImpA, -360, 6));
        ivImpB.setOnClickListener(v -> popupImportant.showAsDropDown(ivImpB, -360, 6));
        ivImpC.setOnClickListener(v -> popupImportant.showAsDropDown(ivImpC, -360, 6));
        ivImpD.setOnClickListener(v -> popupImportant.showAsDropDown(ivImpD, -360, 6));
        // 选择重要性
        impA.setOnClickListener(v -> {
            setImportantLevelImg(DataBean.IMPORTANT_LEVEL_A);
            popupImportant.dismiss();
        });
        impB.setOnClickListener(v -> {
            setImportantLevelImg(DataBean.IMPORTANT_LEVEL_B);
            popupImportant.dismiss();
        });
        impC.setOnClickListener(v -> {
            setImportantLevelImg(DataBean.IMPORTANT_LEVEL_C);
            popupImportant.dismiss();
        });
        impD.setOnClickListener(v -> {
            setImportantLevelImg(DataBean.IMPORTANT_LEVEL_D);
            popupImportant.dismiss();
        });

        etTitle.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_BACK){
                etTitle.clearFocus();
                if (keyCode == KeyEvent.KEYCODE_ENTER){
                    DisplayUtil.hideSoftInput(this);
                }
                return true;
            }
            return false;
        });
        etTitle.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus){
                String title = etTitle.getText().toString();
                if (TextUtils.isEmpty(title) && !isAddData){
                    etTitle.setText(taskBean.getDataTitle());
                }else if (isAddData){
                    taskBean.setDataTitle(title);
                }else if (!TextUtils.isEmpty(title) && !isAddData){
                    taskBean.setDataTitle(title);
                    taskBean.save();
                }
            }
        });

        // 选择清单点击事件
        selectList.setOnClickListener(v -> showSelectListPopupMenu(selectList,
                LitePal.findAll(ListBean.class)));
        // 选择提醒事件点击事件
        selectReminderTime.setOnClickListener(v -> {
            Calendar calendar = Calendar.getInstance();
            TimePickerDialog timePickerDialog = new TimePickerDialog(this,
                    (view, hourOfDay, minute) -> {
                taskBean.setReminderTime(DateUtil.getMillis(year, month, day, hourOfDay, minute));
                taskBean.save();
                selectReminderTime.setText(year+"年"+month+"月"+day+"日"+hourOfDay+":"+minute);
                    }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true);
            DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                    (view, year, month, dayOfMonth) -> {
                this.year = year;
                this.month = month;
                this.day = dayOfMonth;
                timePickerDialog.show();
            }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                    calendar.get(Calendar.DAY_OF_MONTH));
            datePickerDialog.show();
        });
    }

    /**
     * 选择重要性
     * @param level 重要性
     */
    private void setImportantLevelImg(int level){
        ivImpA.setVisibility(View.GONE);
        ivImpB.setVisibility(View.GONE);
        ivImpC.setVisibility(View.GONE);
        ivImpD.setVisibility(View.GONE);
        if (level == DataBean.IMPORTANT_LEVEL_A){
            ivImpA.setVisibility(View.VISIBLE);
            taskBean.setImportantLevel(DataBean.IMPORTANT_LEVEL_A);
        }else if (level == DataBean.IMPORTANT_LEVEL_B){
            ivImpB.setVisibility(View.VISIBLE);
            taskBean.setImportantLevel(DataBean.IMPORTANT_LEVEL_B);
        }else if (level == DataBean.IMPORTANT_LEVEL_C){
            ivImpC.setVisibility(View.VISIBLE);
            taskBean.setImportantLevel(DataBean.IMPORTANT_LEVEL_C);
        }else if (level == DataBean.IMPORTANT_LEVEL_D){
            ivImpD.setVisibility(View.VISIBLE);
            taskBean.setImportantLevel(DataBean.IMPORTANT_LEVEL_D);
        }
        if (!isAddData) taskBean.save();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        if (isAddData){
            taskBean.deleteSubTasks();
        }
        LinearLayoutManager manager = new LinearLayoutManager(this);
        SubTaskRecyclerAdapter adapter = new SubTaskRecyclerAdapter(this, taskBean, taskBean.getSubTasks());
        rvSubTask.setLayoutManager(manager);
        rvSubTask.setAdapter(adapter);
        // 初始化数据
        if (isAddData){
            ivDelete.setVisibility(View.GONE);
            achieveView.setCanClick(false); // 添加时不可点击圆圈
        }else {
            ivSend.setVisibility(View.GONE);
            achieveView.setCanClick(true); // 查看数据时可点击圆圈
            // 初始化数据
            achieveView.setAchieved(taskBean.getIsAchieved());
            DisplayUtil.changeEtContent(etTitle, taskBean.getDataTitle(),
                    taskBean.getIsAchieved());
        }
    }

    /**
     * 显示选择所属清单的PopupMenu
     * @param view 附着控件
     * @param listBeans 总的清单
     */
    private void showSelectListPopupMenu(View view, List<ListBean> listBeans){
        PopupMenu popupMenu = new PopupMenu(this, view);
        Menu menus = popupMenu.getMenu();
        for (int i = 0;i < listBeans.size(); i++){
            menus.add(Menu.NONE, Menu.FIRST + i, i, listBeans.get(i).getListName());
        }
        popupMenu.setOnMenuItemClickListener(item -> {
            ListBean listBean = listBeans.get(item.getItemId() - 1);
            selectList.setText("分类到 <"+listBean.getListName()+">");
            listId = listBean.getListId();
            taskBean.setListId(listBean.getListId());
            return true;
        });
        popupMenu.show();
    }

    @Override
    protected void initView() {
        super.initView();
        achieveView = findViewById(R.id.achieved_view_add);
        toolbar = findViewById(R.id.toolbar_add);
        ivSend = findViewById(R.id.iv_add_toolbar_send);
        ivDelete = findViewById(R.id.iv_data_toolbar_delete);
        etTitle = findViewById(R.id.et_add_title);
        rvSubTask = findViewById(R.id.rv_add_sub);
        selectList = findViewById(R.id.tv_select_list);
        selectReminderTime = findViewById(R.id.tv_select_reminder_time);

        // PopupWindow
        View viewImportant = LayoutInflater.from(this).inflate(R.layout.popup_important_level, null, false);
        popupImportant = new PopupWindow(viewImportant, FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        popupImportant.setOutsideTouchable(true);
        popupImportant.setFocusable(true);
        popupImportant.setAnimationStyle(R.style.popupWindowStyle);
        popupImportant.setElevation(12);
        ivImpA = findViewById(R.id.iv_add_important_level_a);
        ivImpB = findViewById(R.id.iv_add_important_level_b);
        ivImpC = findViewById(R.id.iv_add_important_level_c);
        ivImpD = findViewById(R.id.iv_add_important_level_d);
        impA = viewImportant.findViewById(R.id.tv_popup_important_a);
        impB = viewImportant.findViewById(R.id.tv_popup_important_b);
        impC = viewImportant.findViewById(R.id.tv_popup_important_c);
        impD = viewImportant.findViewById(R.id.tv_popup_important_d);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && !etTitle.isFocused()){
            openNotSaveDialog();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 未保存退出，弹出弹框确认
     */
    private void openNotSaveDialog(){
        if (isAddData && (!"".equals(etTitle.getText().toString()) || taskBean.getSubTasks().size() > 0)){
            // 已修改过但未保存
            SpannableString exitStr = new SpannableString("退出");
            exitStr.setSpan(new ForegroundColorSpan(Color.RED), 0, 2, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            SpannableString cancelStr = new SpannableString("取消");
            cancelStr.setSpan(new ForegroundColorSpan(Color.GRAY), 0, 2, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("内容未保存，是否退出？")
                    .setPositiveButton(exitStr, (dialog, which) -> finishAfterTransition())
                    .setNegativeButton(cancelStr, (dialog, which) -> dialog.dismiss())
                    .create().show();
        }else {
            finishAfterTransition();
        }
    }

    @Override
    protected void onDestroy() {
        if (isAddData){
            // 未保存退出则删除暂存的TaskBean及已添加的SubTask
            Log.e(getClass().getName(), "Delete");
            LitePal.deleteAll(SubTaskBean.class, "taskId = ?", String.valueOf(taskBean.getDataId()));
        }
        super.onDestroy();
    }
}